package com.zhmsky.config.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhmsky.entity.User;
import com.zhmsky.service.UserService;
import lombok.extern.log4j.Log4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author zhmsky
 * @date 2021/12/2 15:
 * @description 自定义realm
 */
@Log4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("正在进行授权、、");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前subject
        Subject subject = SecurityUtils.getSubject();
        //获取当前用户
        User user = (User) subject.getPrincipal();
        //添加当前用户的访问权限
        info.addStringPermission(user.getPermission());
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("正在进行认证、、");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //用户认证（从数据库获取用户信息）
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name",token.getUsername());
        User user = userService.getOne(wrapper);
        //调试打印
        log.debug(user.toString());

        if(user==null){     //用户不存在
            return null;
        }
        //认证成功
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        //将当前用户信息存入session中
        session.setAttribute("userSession",user);
        //密码认证 shiro自动完成   通过将user传入SimpleAuthenticationInfo中，可以通过Principal来获取当前用户信息
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}

